import { onMounted, onBeforeUnmount, ref, watch, type Ref } from 'vue'
import * as echarts from 'echarts'

export function useEchart(elRef: Ref<HTMLElement | null>, getOption: () => echarts.EChartsOption) {
	const chartRef = ref<echarts.ECharts | null>(null)

	const init = () => {
		const el = elRef.value
		if (!el) return
		if (!chartRef.value) {
			chartRef.value = echarts.init(el)
		}
		chartRef.value.setOption(getOption(), true)
		chartRef.value.resize()
	}

	const resize = () => chartRef.value?.resize()

	onMounted(() => {
		init()
		window.addEventListener('resize', resize)
	})

	onBeforeUnmount(() => {
		window.removeEventListener('resize', resize)
		chartRef.value?.dispose()
		chartRef.value = null
	})

	watch(elRef, () => init())

	return {
		chartRef,
		init,
		resize
	}
}
